package org.sft.config;

import javax.annotation.Resource;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * mybatis配置
 * 
 * @author sun
 *
 */
@Configuration
@AutoConfigureAfter({ DataSourceConfig.class })
@MapperScan(basePackages = { "org.sft.**.mapper" })
public class MybatisConfig {
	private static final Logger log = Logger.getLogger(MybatisConfig.class);
	@Resource
	private DataSource dataSource;

	@Bean(name = "sqlSessionFactory")
	@ConditionalOnMissingBean
	public SqlSessionFactory sqlSessionFactory(@Value("${mybatis.typeAliasesPackage}") String typeAliasesPackage, @Value("${mybatis.mapperLocations}") String mapperLocations,
			@Value("${mybatis.configLocation}") String configLocation,@Value("${mybatis.basePackage}") String basePackage) {
		try {
			SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
			sessionFactory.setDataSource(dataSource);
			sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
			sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
			sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
			return sessionFactory.getObject();
		} catch (Exception e) {
			e.printStackTrace();
			log.info("typeAliasesPackage:"+typeAliasesPackage);
			log.info("configLocation:"+configLocation);
			log.error("Could not confiure mybatis session factory");
			return null;
		}
	}
	
}
